/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.sys.web;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.apestar.common.config.Global;
import cn.apestar.common.enums.AuditStateEnum;
import cn.apestar.common.persistence.Page;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.common.web.BaseController;
import cn.apestar.core.base.BaseMessage;
import cn.apestar.modules.common.feedback.service.SysImageService;
import cn.apestar.modules.sys.entity.Institution;
import cn.apestar.modules.sys.service.InstitutionService;
import cn.apestar.modules.sys.service.UserAndInstituionService;
import cn.apestar.modules.sys.service.UserService;
import cn.apestar.user.provider.institution.enums.InstitutionImageTypeEnum;
import cn.apestar.util.AuthUtil;

/**
 * 机构表Controller
 * @author LVH
 * @version 2016-02-21
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/institution")
public class InstitutionController extends BaseController {

    @Autowired
    private InstitutionService institutionService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAndInstituionService userAndInstituionService;

    @Autowired
    RestTemplate restTemplateApestar;

    @Autowired
    private SysImageService sysImageService;

    @ModelAttribute
    public Institution get(@RequestParam(required = false) String id) {

        Institution entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = institutionService.get(id);
        }
        if (entity == null) {
            entity = new Institution();
        }
        return entity;
    }

    @RequestMapping(value = {"list" , ""})
    public String list(Institution institution, HttpServletRequest request, HttpServletResponse response, Model model) {

        Page<Institution> page = institutionService.findPage(new Page<Institution>(request, response), institution);
        model.addAttribute("page", page);
        model.addAttribute("institution", institution);
        // userAndInstituionService.findInstitutionTgList(page.getList());
        return "modules/sys/Institution/institutionList";
    }

    @RequestMapping(value = "form")
    public String form(Institution institution, Model model) {

        if (StringUtils.isNoneEmpty(institution.getOnBusinessWeekday())) {
            String[] s = institution.getOnBusinessWeekday().split(",");
            institution.setOnBusinessWeekdayList(Arrays.asList(s));
        }
        model.addAttribute("institution", institution);
        if (institution != null && StringUtils.isNoneEmpty(institution.getId())) {
            // // 保存资质
            sysImageService.setImage(institution, "certificate", InstitutionImageTypeEnum.INSTITUTION_CARD_FACE.getValue());
            // // 环境图片
            // List<WtImage> environmentList = institution.getEnvironmentList();
            sysImageService.setImage(institution, "environment", InstitutionImageTypeEnum.INSTITUTION_CARD_BACK.getValue());
            // List<WtImage> equipmentList = institution.getEquipmentList();
            sysImageService.setImage(institution, "equipment", InstitutionImageTypeEnum.INSTITUTION_BUSINESS.getValue());
        }
        return "modules/sys/Institution/institutionForm";
    }

    @RequestMapping(value = "save")
    public String save(Institution institution, Model model, RedirectAttributes redirectAttributes) {

        if (institution.getOnBusinessWeekdayList().size() > 0) {
            StringBuffer s = new StringBuffer();
            List list = institution.getOnBusinessWeekdayList();
            for (int i = 0; i < list.size(); i++) {
                s.append(list.get(i).toString());
                s.append(",");
                institution.setOnBusinessWeekday(s.toString());
            }
        }
        if (!beanValidator(model, institution)) {
            return form(institution, model);
        }
        institutionService.save(institution);
        addMessage(redirectAttributes, "保存机构表成功");
        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

    @RequestMapping(value = "delete")
    public String delete(Institution institution, RedirectAttributes redirectAttributes) {

        institutionService.delete(institution);
        addMessage(redirectAttributes, "删除机构表成功");
        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

    @RequestMapping(value = "updateHot/id/{id}/hot/{hot}")
    public String updateHot(@PathVariable("id") String id, @PathVariable("hot") String hot, RedirectAttributes redirectAttributes) {
        Institution institution = new Institution();
        institution.setHot(hot);
        institution.setId(id);
        institutionService.updateState(institution);
        addMessage(redirectAttributes, "更新状态成功");
        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

    @RequestMapping(value = "updateState/id/{id}/vipType/{vipType}")
    public String updateState(@PathVariable("id") String id, @PathVariable("vipType") String vipType, RedirectAttributes redirectAttributes) {
        Institution institution = new Institution();
        institution.setVipType(vipType);
        institution.setId(id);
        institutionService.updateState(institution);
        addMessage(redirectAttributes, "更新状态成功");
        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

    @RequestMapping(value = "updateAuth/id/{id}/auth/{authType}")
    public String updateAuth(@PathVariable("id") String id, @PathVariable("authType") String authType, RedirectAttributes redirectAttributes) {
        Institution institution = new Institution();

        if ("2".equals(authType)) {
            institution.setAuthentication(AuditStateEnum.TG_TG.getValue());
            institution.setState(AuditStateEnum.TG_TG.getValue());
        }

        if ("3".equals(authType)) {
            institution.setAuthentication(AuditStateEnum.TG_NG.getValue());
            institution.setState(AuditStateEnum.TG_NG.getValue());
        }
        institution.setId(id);

        if (testAuth(institution, redirectAttributes)) {
            institutionService.updateState(institution);
            addMessage(redirectAttributes, "更新审核状态成功");
        }

        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

    public Boolean testAuth(Institution institution, RedirectAttributes redirectAttributes) {
        Boolean flag = false;

        String url = Global.getConfig("USER_CLEAR_URL") + "motormaster/motorInstitution/audit";

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        AuthUtil.putAuth(headers);

        HttpEntity<Institution> formEntity = new HttpEntity<Institution>(institution, headers);

        try {
            ResponseEntity<BaseMessage> resultOn = restTemplateApestar.exchange(url, HttpMethod.POST, formEntity, BaseMessage.class);

            if (resultOn.getStatusCode().is2xxSuccessful()) {
                flag = true;
            }
            return flag;
        } catch (Exception e) {

            addMessage(redirectAttributes, "审核操作失败 可能原因：1.查无此门店     2.该门店已经审核    3.提交数据不足或有误");

            return flag;
        }

    }

    @RequestMapping(value = "updateDel/id/{id}/op/{delFlag}")
    public String updateDel(@PathVariable("id") String id, @PathVariable("delFlag") String delFlag, RedirectAttributes redirectAttributes) {
        Institution institution = new Institution();
        institution.setDelFlag(delFlag);
        institution.setId(id);
        institutionService.updateDel(institution);
        addMessage(redirectAttributes, "更改操作成功");
        return "redirect:" + Global.getAdminPath() + "/sys/institution/?repage";
    }

}